import axios from 'axios'
import { getLocalStorage } from '@/utils/storage'
import store from '@/store'
import { Notification } from 'element-ui'

const request = axios.create({
  baseURL: 'http://interview-api-t.itheima.net',
  timeout: 4000
})

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = getLocalStorage('token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  })

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    return response
  }, function (error) {
    if (error.response.data.code === 401) {
      store.commit('user/delToken')
      Notification({
        type: 'error',
        message: '登录状态无效，请重新登录',
        duration: 1500,
        title: '错误'
      })
      return Promise.reject(error)
    }
    return Promise.reject(error)
  })

export default request
